<?php
/**
 * 邮箱同步简历
 *
 *  yum install pam-devel libc-client libc-client-devel -y
 *  cd /root/lnmp1.5/src/php-7.2.6/ext/imap
 *  ./configure --with-php-config=/usr/local/php/bin/php-config --with-kerberos --with-imap-ssl
 *  make && make install
 */

namespace app\common\logic;

class ResumeEmailLogic {

    private $emailBox = '';
    private $emailHosts = [
        '163' => 'pop.163.com',
        'qq' => 'pop.qq.com'
    ];

    public function __construct($username, $password) {
        $emailType = $this->getEmailType($username);
        $host = $this->emailHosts[$emailType];
        $connect = '{' . $host . ':110/pop3}INBOX';
        $this->emailBox = imap_open($connect, $username, $password);
        if (!$this->emailBox) {
            echo 'Error: Login failed ' . imap_last_error();
            exit;
        }
    }

    public function getEmailType($username) {
        preg_match('/.*@(.*)\./', $username, $matches);
        return $matches[1] ?? '';
    }

    /**
     * 获取邮件总数
     * @return int 条数
     */
    public function getTotalNum() {
        return imap_num_msg($this->emailBox);
    }

    /**
     * 获取邮件正文
     * @param int 邮件id HTML格式
     * @return string body
     */
    public function getBody($id, $is_html = false) {
        try {
            $type = imap_fetchstructure($this->emailBox, $id);
            imap_errors();
            if ($type->subtype == 'HTML') {
                return quoted_printable_decode(imap_fetchbody($this->emailBox, $id, 1));
            } else {
                if (isset($type->parts) && $type->parts[0]->subtype == 'HTML') {
                    return imap_qprint(imap_fetchbody($this->emailBox, $id, 1));
                }
                if ($type->parts[0]->subtype == 'ALTERNATIVE') {
                    $body = imap_fetchbody($this->emailBox, $id, 1.2);
                    if ($body == null) {
                        $body = imap_fetchbody($this->emailBox, $id, 1);
                    }
                    $body = quoted_printable_decode($body);
                    return $body;
                }
            }
            if ($type->subtype == 'ALTERNATIVE') {
                if (!$is_html) {
                    return mb_convert_encoding(base64_decode(imap_fetchbody($this->emailBox, $id, 1)), 'UTF-8', ["ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5']);
                } else {
                    return mb_convert_encoding(base64_decode(imap_fetchbody($this->emailBox, $id, 2)), 'UTF-8', ["ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5']);
                }
            }

            $message = imap_qprint(imap_fetchbody($this->emailBox, $id, 1.2));
            $message = base64_decode($message);
            $encode = mb_detect_encoding($message, ["ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5']);
            $message = mb_convert_encoding($message, 'UTF-8', $encode);
            return $message;
        } catch (\Exception $e) {
//            print_r($e->getTraceAsString());
            dolog(__METHOD__.'Error',[$e->getMessage(),$e->getFile(),$e->getLine()]);
            return '';
        }
    }

    /**
     * 获取邮件头信息
     * @param int 邮件id
     * @return array from发送者 formName发送者名称 Subject标题 time
     */
    public function getHeader($id) {
        try {
            $str = imap_headerinfo($this->emailBox, $id);
            $arr = [
                'from' => $str->from[0]->mailbox . '@' . $str->from[0]->host,
                'fromName' => mb_convert_encoding(imap_mime_header_decode($str->from[0]->personal)[0]->text, 'UTF-8', ["ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5']),
                'subject' => '',
                'time' => $str->udate

            ];
            foreach (imap_mime_header_decode($str->Subject) as $value) {
                $arr['subject'] .= mb_convert_encoding($value->text, 'UTF-8', $value->charset);
            }

            return $arr;
        } catch (\Exception $e) {
            return [];
        }
    }

    /**
     * 下载附件
     * @param $id
     * @return false|string
     */
    public function getAttachment($id) {
        try {
            $dir = 'upload/resume_email/' . date('Ymd') . '/';
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
            $str = imap_fetchstructure($this->emailBox, $id);
            imap_errors();

            if (!isset($str->parts)) {
                return false;
            }
            foreach ($str->parts as $index => $part) {
                if (isset($part->disposition) && strtolower($part->disposition) === 'attachment') {
                    $part->parameters = array_values(array_filter($part->parameters, function ($item) {
                        return $item->attribute === 'NAME';
                    }));

                    $attachment = $part->parameters[0]->value;
                    $filename = '';
                    foreach (imap_mime_header_decode($attachment) as $value) {
                        $filename .= mb_convert_encoding($value->text, 'UTF-8', ["ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5']);
                    }
                    $fileType = strtolower(trim(substr(strrchr($filename, '.'), 1)));
                    if (!in_array($fileType, ['pdf', 'docx'])) {
                        continue;
                    }
                    $filename = $dir . md5(trim($filename)) . '.' . $fileType;
                    $attachment = imap_fetchbody($this->emailBox, $id, $index + 1);
                    file_put_contents($filename, base64_decode($attachment));
                    return $filename; //只获取第一个附件
                }
            }
        } catch (\Exception $e) {

        }
        return false;
    }

    public function close() {
        imap_errors();//清除错误堆栈
        imap_close($this->emailBox);
    }

}